package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"shops/cache"
	"shops/models"
)

type ShopsController struct {
	beego.Controller
}
type Response struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *ShopsController) Add() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	name := c.GetString("name")
	address := c.GetString("address")
	if name == "" || address == "" {
		c.Data["json"] = Response{
			Code: 500,
			Msg:  "门店信息不可为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	var s models.Shops
	s.Name = name
	s.Address = address
	err := s.Add()
	if err != nil {
		c.Data["json"] = Response{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	shops, _ := s.GetList()
	jsonData, _ := json.Marshal(shops)
	cache.Rdb.Set(cache.Ctx, "shop", jsonData, 0)
	c.Data["json"] = Response{
		Code: 200,
		Msg:  "添加成功",
		Data: nil,
	}
	c.ServeJSON()
	return
}
func (c *ShopsController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	var shops []models.Shops
	cacheData := cache.Rdb.Get(cache.Ctx, "shop").Val()
	if cacheData == "" {
		models.DB.Find(&shops)
		jsonData, _ := json.Marshal(shops)
		cache.Rdb.Set(cache.Ctx, "shop", jsonData, 0)
	} else {
		json.Unmarshal([]byte(cacheData), &shops)
	}
	c.Data["json"] = Response{
		Code: 200,
		Msg:  "查询成功",
		Data: shops,
	}
	c.ServeJSON()
	return
}
func (c *ShopsController) Update() {
	id, _ := c.GetInt("id")
	if id < 1 {
		c.Data["json"] = Response{
			Code: 500,
			Msg:  "参数错误",
		}
		c.ServeJSON()
		return
	}
	var s models.Shops
	s.ID = uint(id)
	s.Name = c.GetString("name")
	s.Address = c.GetString("address")
	err := s.Update()
	if err != nil {
		c.Data["json"] = Response{
			Code: 500,
			Msg:  "更新失败",
		}
		c.ServeJSON()
		return
	}
	shops, _ := s.GetList()
	jsonData, _ := json.Marshal(shops)
	cache.Rdb.Set(cache.Ctx, "shop", jsonData, 0)
	c.Data["json"] = Response{
		Code: 200,
		Msg:  "更新成功",
	}
	c.ServeJSON()
	return
}
